package com.me.bbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.me.bbs.dto.ForumFollowingDTO;
import com.me.bbs.entity.Forum;
import com.me.bbs.entity.ForumFollowing;
import com.me.bbs.mapper.ForumFollowingMapper;
import com.me.bbs.service.IForumFollowingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.me.bbs.service.IForumService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lm
 * @since 2023-01-22
 */
@Service
public class ForumFollowingServiceImpl extends ServiceImpl<ForumFollowingMapper, ForumFollowing> implements IForumFollowingService {
    @Resource
    ForumFollowingMapper forumFollowingMapper;
    @Resource
    IForumService forumService;
    @Override
    public Page<ForumFollowingDTO> getForumFollowingList(Page<ForumFollowing> page, Wrapper<ForumFollowing> wrapper) {
        return forumFollowingMapper.selectForumFollowingDtoList(
                page,wrapper
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void follow(ForumFollowing forumFollowing, Boolean isFollow) throws Exception {
        String setSql = "subscribe = subscribe + 1";
        if(isFollow) {
            boolean save = this.save(forumFollowing);
            if(!save) throw new Exception("保存出错");
        } else  {
            setSql = "subscribe = subscribe - 1";
            boolean remove = this.lambdaUpdate().eq(ForumFollowing::getForum, forumFollowing.getForum())
                    .eq(ForumFollowing::getUser, forumFollowing.getUser())
                    .remove();
            if(!remove) throw new Exception("删除出错");
        }
        forumService.lambdaUpdate()
                .eq(Forum::getId, forumFollowing.getForum())
                .setSql(setSql)
                .update();
    }
}
